// Package sms
// Created by GoLand
// @User: lenora
// @Date: 2023/12/27
// @Time: 13:28

package sms

import (
	"camp/microbook/pkg/limiter"
	"context"
	"errors"
)

var ErrLimited = errors.New("被限流")

type RateLimiter interface {
	Limit(ctx context.Context) error
}

type rateLimiter struct {
	limiter limiter.Limiter
	key     string
}

func NewRateLimitService(l limiter.Limiter, key string) RateLimiter {
	return &rateLimiter{
		limiter: l,
		key:     key,
	}
}

func (t *rateLimiter) Limit(ctx context.Context) error {
	limited, err := t.limiter.Limit(ctx, t.key)
	if err != nil {
		return err
	}
	if limited {
		return ErrLimited
	}
	return nil
}
